package com.xpert.action.board;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import com.xpert.action.CommandAction;
import com.xpert.beans.Board;
import com.xpert.common.Constants;
import com.xpert.common.Util;
import com.xpert.dao.BoardDao;

public class WriteProcAction implements CommandAction {

    @Override
    public String requestProc(HttpServletRequest request,
	    HttpServletResponse response) throws Throwable {

    	// If the client access via get method even you only allow post method,
    	// then you just return him to the place where he was.
    	String accessMethod = request.getMethod();
    	if(accessMethod.equals(Constants.ACCESS_METHOD_GET) ) {
  	    request.setAttribute("message", true);
  	    request.setAttribute("url", "write.do");

  	    return "redirect.jsp";
    	}

    	int maxPostSize = 10 * 1024 * 1024;
    	String saveDirectory = request.getSession().getServletContext().getRealPath(Constants.FILE_SAVE_DIR); // getRealPath("/upload");
    	MultipartRequest multi = null;
    	
    	try {
    		multi = new MultipartRequest(request, saveDirectory, maxPostSize, "UTF-8", new DefaultFileRenamePolicy()	);
    	}
    	catch (IOException e) {
    		e.printStackTrace();
    	}

    	String fileName = multi.getFilesystemName("fileName");
    	// String userID = "guest"; 
      // fileName = userID + fileName.substring(fileName.lastIndexOf("."));		// it will store the file as like "guest.txt".

    	String title = Util.checkNull(multi.getParameter("title"));
    	String writer = Util.checkNull(multi.getParameter("writer"));
    	int count = 0;
    	String content = Util.checkNull(multi.getParameter("content"));
    	String regip = Util.checkNull(request.getRemoteAddr());

    	// check for abnormal access
    	if(title.equals(Constants.EMPTY_STR) ||
    		content.equals(Constants.EMPTY_STR) ||
    		writer.equals(Constants.EMPTY_STR) ) {

    	    request.setAttribute("message", true);
    	    request.setAttribute("url", "write.do");

    	    return "redirect.jsp";
    	    // || !Pattern.matches("^[_0-9a-zA-Z-]+@[0-9a-zA-Z-]+(.[_0-9a-zA-Z-]+)*$", email)	// checking email
    	}
    	else {
    	    Board board = new Board();
    	    board.setTitle(title);
    	    board.setWriter(writer);
    	    board.setCount(count);
    	    board.setContent(content);
    	    board.setRegip(regip);
    	    board.setFileName(fileName);
    
    	    BoardDao.getInstance().insertArticle(board);

    	    return "list.do";
    	}
	
   }
    
}
